package com.xwaiy.xwaiyrpc.bootstrap;

import com.xwaiy.xwaiyrpc.RpcApplication;
import com.xwaiy.xwaiyrpc.config.RegistryConfig;
import com.xwaiy.xwaiyrpc.config.RpcConfig;
import com.xwaiy.xwaiyrpc.exception.RpcException;
import com.xwaiy.xwaiyrpc.exception.enums.ErrorCode;
import com.xwaiy.xwaiyrpc.model.ServiceMetaInfo;
import com.xwaiy.xwaiyrpc.model.ServiceRegisterInfo;
import com.xwaiy.xwaiyrpc.registry.LocalRegistry;
import com.xwaiy.xwaiyrpc.registry.Registry;
import com.xwaiy.xwaiyrpc.registry.RegistryFactory;
import com.xwaiy.xwaiyrpc.server.tcp.VertxTcpServer;

import java.util.List;

/**
 * 服务提供初始化
 * @Author Xwaiy
 * @Date 2025/9/5 11:03
 **/
public class ServerBootstrap {

    /**
     * 初始化
     */
    public static void init(List<ServiceRegisterInfo<?>> list) {
        // TO 框架初始化
        RpcApplication.init();

        final RpcConfig rpcConfig = RpcApplication.getRpcConfig();

        // TO 注册服务
        for (ServiceRegisterInfo<?> info : list) {
            String serviceName = info.getServiceName();
            try {
                // 创建服务实例并注册（使用无参构造函数）
                Object serviceImpl = info.getImplClass().getDeclaredConstructor().newInstance();
                LocalRegistry.registerService(serviceName, serviceImpl);
            } catch (Exception e) {
                throw new RpcException(ErrorCode.SYSTEM_ERROR, "创建服务实例失败: " + serviceName + ", 请确保服务类有无参构造函数", e);
            }

            // TO 注册服务到注册中心
            RegistryConfig registryConfig = rpcConfig.getRegistryConfig();
            Registry registry = RegistryFactory.getInstance(registryConfig.getRegistry());
            ServiceMetaInfo serviceMetaInfo = new ServiceMetaInfo();
            serviceMetaInfo.setServiceName(serviceName);
            serviceMetaInfo.setServiceHost(rpcConfig.getServerHost());
            serviceMetaInfo.setServicePort(rpcConfig.getServerPort());

            try{
                registry.register(serviceMetaInfo);
            }catch (Exception e) {
                throw new RpcException(ErrorCode.REGISTRY_SERVICE_REGISTER_FAILED, serviceName+" register error",e);
            }
        }

        // TO 启动服务器
        VertxTcpServer server = new VertxTcpServer();
        server.doStart(rpcConfig.getServerPort());
    }
}
